package com.joysuch.wwyt.core.service.impl;

import com.joysuch.wwyt.common.service.MailSettingService;
import com.joysuch.wwyt.core.entity.MailSetting;
import com.joysuch.wwyt.core.service.MailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Service;

/**
 * @Author ZhangDong
 * @Date 2020/6/8 15:56
 */
@Service
@Slf4j
public class MailServiceImpl implements MailService {

    @Value("${spring.mail.subject}")
    private String subject;
    @Value("${spring.mail.username}")
    private String from;
    @Autowired
    private MailSettingService mailSettingService;

    private final static String MAIL_SUBJECT_DEFAULT = "系统验证码";

    @Override
    public void setTextMail(String[] toMails, String text) {
        MailSetting mailSetting = mailSettingService.findOne();
        if (mailSetting == null) {
            throw new IllegalArgumentException("请先配置邮箱服务器");
        }
        JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
        javaMailSender.setDefaultEncoding("UTF-8");
        javaMailSender.setHost(mailSetting.getHost());
        javaMailSender.setUsername(mailSetting.getUserName());
        javaMailSender.setPassword(mailSetting.getPassword());
        javaMailSender.setProtocol(mailSetting.getProtocol());
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        // 设置收件人，寄件人
        simpleMailMessage.setTo(toMails);
        simpleMailMessage.setFrom(mailSetting.getUserName());
        // properties 配置文件中中文乱码问题
        simpleMailMessage.setSubject(MAIL_SUBJECT_DEFAULT);
        simpleMailMessage.setText(text);
        // 发送邮件
        javaMailSender.send(simpleMailMessage);
        log.info("邮件已发送,to:{},内容:{}", toMails, text);
    }
}
